import joblib
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import accuracy_score
from sklearn import metrics
from mdp_random import data_handle
from mdp_LDA import plot_roc
from mdp_all import mdp_data

def KNN_algorithm(filename,num=0):
    datasets, labels, count = data_handle(filename)  # 对数据集进行处理
    print("Running for Method: LDA")
    X = datasets[:]
    y = labels[:]
    print("len of X", len(X))
    print("no of column", len(datasets[0]))

    # 数据预处理
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)
    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.25, random_state=42)

    # 创建KNN分类器对象
    k = 5  # K值，即邻居的数量
    knn = KNeighborsClassifier(n_neighbors=k)
    # 在训练集上拟合模型
    knn.fit(X_train, y_train)
    joblib.dump(knn, 'files/knn.pkl')
    # 在测试集上进行预测
    y_pred = knn.predict(X_test)

    # 计算准确率
    accuracy = accuracy_score(y_test, y_pred)
    print("Accuracy:", accuracy)
    # 训练

    auc = metrics.accuracy_score(y_test, y_pred)
    macro = metrics.precision_score(y_test, y_pred, average='macro')
    micro = metrics.precision_score(y_test, y_pred, average='micro')
    macro_recall = metrics.recall_score(y_test, y_pred, average='macro')
    weighted = metrics.f1_score(y_test, y_pred, average='weighted')
    print('准确率:', auc)  # 预测准确率输出
    print('宏平均精确率:', macro)  # 预测宏平均精确率输出
    print('微平均精确率:', micro)  # 预测微平均精确率输出
    print('宏平均召回率:', macro_recall)  # 预测宏平均召回率输出
    print('平均F1-score:', weighted)  # 预测平均f1-score输出
    print('混淆矩阵输出:\n', metrics.confusion_matrix(y_test, y_pred))  # 混淆矩阵输出
    print('分类报告:', metrics.classification_report(y_test, y_pred))  # 分类报告输出
    # Plot of a ROC curve for a specific class
    if(num==0):
        plot_roc(y_test, y_pred, auc, macro, macro_recall, weighted)  # 绘制ROC曲线并求出AUC值
    else:
        mdp_data.add_data(mdp_data,y_test, y_pred, auc, macro, macro_recall, weighted)

if __name__=='__main__':
    KNN_algorithm('MDP/KC3.csv')

